package com.kx.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kx.dao.QueryDao;
import com.kx.entity.City;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class QueryCityListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取请求传过来的，省份id
        String strProvinceId = request.getParameter("proid");
        String json = "{}";
        if (strProvinceId != null && strProvinceId.trim().length() > 0) {
            QueryDao dao = new QueryDao();
            List<City> cities = dao.queryCityList(Integer.valueOf(strProvinceId));
            System.out.println(cities);
            //把list转为json格式的数据，输出给ajax请求
            if (cities != null) {
                //调用jackson的工具库，实现List--json
                ObjectMapper om = new ObjectMapper();
                json = om.writeValueAsString(cities);
            }
            //输出json数据，响应ajax请求，返回数据
            response.setContentType("application/json;charset=utf-8");
            PrintWriter pw = response.getWriter();
            pw.println(json);
            pw.flush();
            pw.close();
        }

    }
}
